package models

import (
	"github.com/beego/beego/v2/client/orm"
)

type SchoolQueryParam struct {
	BaseQueryParam
	Filter string
}

type Schools struct {
	Id         int64
	SchoolName string
	Address    string
	Street     string
	Telephone  string
	Status     int
	Message    string
}

func SchoolsTableName() string {
	return TableName("set_schools")
}

func (a *Schools) TableName() string {
	return SchoolsTableName()
}

/**
* 添加学校
 */
func (a *Schools) SchoolAdd() (int64, error) {
	a.Status = 1
	return orm.NewOrm().Insert(a)
}

//修改学校
func (a *Schools) SchoolEdit(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}

//单条学校
func GetSchoolById(id int64) (*Schools, error) {
	r := new(Schools)
	r.Id = id
	err := orm.NewOrm().Read(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

//查询无分页数据
func SchoolList(params *SchoolQueryParam) []*Schools {

	query := orm.NewOrm().QueryTable(SchoolsTableName())
	data := make([]*Schools, 0)
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	cond := orm.NewCondition()

	if params.Filter != "" {
		cond = cond.And("school_name__contains", params.Filter)
	}
	query = query.SetCond(cond)

	query = query.Filter("status", 1)

	query.OrderBy(sortorder).All(&data)

	return data

}

//查询分页数据
func SchoolPageList(params *SchoolQueryParam) ([]*Schools, int64) {

	query := orm.NewOrm().QueryTable(SchoolsTableName())
	data := make([]*Schools, 0)
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	cond := orm.NewCondition()

	if params.Filter != "" {
		cond = cond.And("school_name__contains", params.Filter)
	}
	query = query.SetCond(cond)

	query = query.Filter("status", 1)

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total

}
